//
//  NetworkClient+Study.swift
//  SitPosition
//
//  Created by apple on 2019/2/10.
//  Copyright © 2019 apple. All rights reserved.
//

import Foundation


/**
 * 学生学习数据接口
 */
extension NetworkApi {
    
    // 家长获取近半个小时学习姿态
    public static func fetchStudentHalfHourPoseData() -> NetworkApi {
        return NetworkApi("/userCenter/settingPostures/search/findByStartTime", method: .get)
    }
    
    // 批量上传用户坐姿信息
    public static func batchSaveStudentPoseData() -> NetworkApi {
        return NetworkApi("/userCenter/settingPostures/action/batchSave", method: .post)
    }
}

extension NetworkClient {
    
    // 用户-获取某天学习统计数据
    func fetchStudentHalfHourPoseData(startTime: Date,
                                      pageNum: Int,
                                      pageSize: Int = 15,
                                      success: DataParamCallback?,
                                      failure: ErrorCallback?) {
        // 指定开始时间、分页参数
        let params: [String : Any] = [
            "startTime": Int64(startTime.timeIntervalSince1970 * 1000),
            "pageNum": pageNum,
            "pageSize": pageSize
        ]
        let completionHandler = commonDataRequestCompletion(success: success, failure: failure)
        NetworkClient.instance.request(NetworkApi.fetchStudentHalfHourPoseData(), params: params, headers: nil)
            .responseData(completionHandler: completionHandler)
    }
    
    // 批量上传用户坐姿信息
    func batchSaveStudentPoseData(contents: [StudyPoseData],
                                  success: DataParamCallback?,
                                  failure: ErrorCallback?) {
        // 指定姿态信息集合
        let encoder: JSONEncoder = JSONEncoder()
        let contentsJSONObj: Any
        do {
            let contentsData = try encoder.encode(contents)
            contentsJSONObj = try JSONSerialization.jsonObject(with: contentsData, options: JSONSerialization.ReadingOptions.allowFragments)
        } catch {
            failure?(error)
            return
        }
        let params: [String : Any] = [
            "settingPostures": contentsJSONObj
        ]
        let completionHandler = commonDataRequestCompletion(success: success, failure: failure)
        NetworkClient.instance.request(NetworkApi.batchSaveStudentPoseData(), params: params, headers: nil)
            .responseData(completionHandler: completionHandler)
    }
}
